package org.streets.workflow.engine.entities;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * 
 */
@Entity
@Table(name="WF_RT_PROCESS_VAR")
public class ProcessVariant {
	@Id
	private String id = null;
	@Column
	private String processId = null;
	@Column
	private String name = null;
	@Column
	private String value = null;
	@Column
	private String type = null;
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getProcessId() {
		return processId;
	}

	public void setProcessId(String processInstanceId) {
		this.processId = processInstanceId;
	}


	public Object getValue() {
		if (Integer.class.getName().equals(this.type)
				|| int.class.getName().equals(this.type)) {
			return Integer.parseInt(this.value);
		} else if (Long.class.getName().equals(this.type)
				|| long.class.getName().equals(this.type)) {
			return Long.parseLong(this.value);
		} else if (String.class.getName().equals(this.type)) {
			return this.value;
		} else if (Float.class.getName().equals(this.type)
				|| float.class.getName().equals(this.type)) {
			return Float.parseFloat(this.value);
		} else if (Double.class.getName().equals(this.type)
				|| double.class.getName().equals(this.type)) {
			return Double.parseDouble(this.value);
		} else if (Boolean.class.getName().equals(this.type)
				|| boolean.class.getName().equals(this.type)) {
			return Boolean.parseBoolean(this.value);
		} else if (Date.class.getName().equals(this.type)) {
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HHmmss");
			try {
				return formatter.parse(this.value);
			} catch (ParseException e) {
				return null;
			}
		}
		return value;
	}

	public void setValue(Object v) {
		this.value = String.valueOf(v);
	}

	public String getType() {
		return type;
	}

	public void setType(String valueType) {
		this.type = valueType;
	}

	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (!(obj instanceof ProcessVariant))
			return false;
		ProcessVariant var = (ProcessVariant) obj;
		if (var.getProcessId().equals(this.getProcessId()) && var.getName().equals(this.getName())) {
			return true;
		} else {
			return false;
		}
	}

	public int hashCode() {
		if (this.getProcessId() == null && this.getName() == null) {
			return super.hashCode();
		} else {
			// FIXME ...
			return this.getProcessId().hashCode() + this.getName().hashCode();
		}
	}
}
